package br.com.amadeus.android.activities.home;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Config;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.entities.CourseUser;
import br.com.amadeus.android.entities.Forum;
import br.com.amadeus.android.entities.Resource;
import br.com.amadeus.android.entities.SocialHistory;
import br.com.amadeus.android.util.AccessMode;
import br.com.amadeus.android.util.ConstantsAmadeusDroid;
import br.com.amadeus.android.util.ImageUtil;
import br.com.amadeus.android.util.JSONReader;
import br.com.amadeus.android.util.RESTFileContent;

public class FirstInnerSyncActivity extends Activity implements OnClickListener{
	
	FacadeAmadeusDroid facade = FacadeAmadeusDroid.getInstance(this);
	ProgressThread progressThread;
    ProgressDialog progressDialog;
	Button button;
	Button button2;
	EditText login;
	EditText end;
	EditText password;
	String endereco;
	String userLogin;
	String userPassword;
	String enderecoFinal;
	String baseUrl;
    InputStream input;
    InputStream inputMaterials;
    int countCourses = 0;
    long lengthOfFile = 0;
    boolean hostInvalido = false;
    boolean threadException = false;
        
	protected static final String CATEGORIA = "curso";
	static final int PROGRESS_DIALOG = 0;
	
	Thread syncThread;
	
	
	private static final String[] URLS = {ConstantsAmadeusDroid.URL_DEFAULT/*, ConstantsAmadeusDroid.URL_LOCALHOST*/};
	
		 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.amadeus_screen_2);
		
		//Testa se o modo de Acesso foi alterado para Offline pelo usuário no primeiro acesso.
		//Caso contrário, a Activity já seta o modo online em preferences
		if (!AccessMode.modifiedByUser) {
			SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
			SharedPreferences.Editor editor = getPrefs.edit();
			editor.putString("listPref", Integer.toString(ConstantsAmadeusDroid.MODO_ONLINE));
			editor.commit();
		}
			
		initUrls();
		
		button = (Button) findViewById(R.id.s2avancar);
		button2 = (Button) findViewById(R.id.s2voltar);
		login = (EditText) findViewById(R.id.etLogin);
		password = (EditText) findViewById(R.id.etPassword);
		end = (EditText) findViewById(R.id.etURL);
				
		//A��o bot�o Avan�ar
		button.setOnClickListener(this);
		
		//A��o bot�o Voltar
		button2.setOnClickListener(this);
		//video de libras
		ImageButton librasBt = (ImageButton)findViewById(R.id.botaoLibras2);
        librasBt.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent it = new Intent("ABRIR_LIBRAS");
				it.putExtra("video_libras", "FirstInnerSync.wmv");
				startActivity(it);
				
			}
		});
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		try {
			dismissDialog(PROGRESS_DIALOG);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
		
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		finish();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
        case PROGRESS_DIALOG:
            progressDialog = new ProgressDialog(FirstInnerSyncActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setTitle("Amadeus");
            progressDialog.setMessage("Buscando por dados, por favor aguarde...");
            progressDialog.setIndeterminate(false);
            progressDialog.setMax(100);
            return progressDialog;
        default:
            return null;
        }
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch(id) {
        case PROGRESS_DIALOG:
            progressDialog.setProgress(0);
            progressThread = new ProgressThread(handler);
            progressThread.start();
		}
	}
	
	// Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int total = msg.arg1;
            progressDialog.setProgress(total);
            if (total >= 100){
                //dismissDialog(PROGRESS_DIALOG);
                progressThread.setState(ProgressThread.STATE_DONE);
            }
        }
    };
    	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater blowUp = getMenuInflater();
		blowUp.inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.config:
			startActivity(new Intent("HOME_SETTINGS"));
			break;
		}
		return super.onOptionsItemSelected(item);
	}
		
	private void syncAmadeus(final String courses, final int countCourses, final Config config){
		syncThread = new Thread() {
			@Override
			public void run(){
				try {
					ArrayList<Course> listCourses = JSONReader.getListCourses(courses, countCourses);
		            ArrayList<CourseUser> listCourseUser = JSONReader.getListCourseUser(courses);
		            	            
		            String enderecoImagem = config.getAmadeus_url() + 
		            ConstantsAmadeusDroid.HOST_AMADEUS_WEB_PHOTO + login.getText().toString().trim();
		            
		            String url = config.getAmadeus_url() + 
		            ConstantsAmadeusDroid.HOST_AMADEUS_WEB_HISTORY;
		            RESTFileContent rfc = new RESTFileContent();
		            InputStream is2 = rfc.getRESTFileContent(url);
		            String historic = rfc.toString(is2);
		            ArrayList<SocialHistory> listSocial = JSONReader.getAmadeusHistoric(historic);
		            
		            for (SocialHistory obj : listSocial) {
		            	String endImageHist = config.getAmadeus_url() + 
			            ConstantsAmadeusDroid.HOST_AMADEUS_WEB_PHOTO + obj.getUserLogin();
		            	ImageUtil.saveImageUser(endImageHist, obj.getUserName());
					}
		            for (Course course : listCourses) {
						ArrayList<Resource> res = course.getResourceList();
						for (Resource resource : res) {
							if (resource.getForum() != null) {
								ArrayList<br.com.amadeus.android.entities.Message> listMsg = resource.getForum().getListMessages();
								getPhotoAuthors(listMsg, config);
							}
						}
					}
		            ImageUtil.saveImageUser(enderecoImagem);
		            facade.syncronizeAmadeus(listCourses, listCourseUser, config, listSocial);
		            
				} catch (Exception e) {
					Log.e(CATEGORIA, e.getMessage(), e);
					threadException = true;
				}
				
			}
		};
		syncThread.start();
	}
	
	private void getPhotoAuthors(
			ArrayList<br.com.amadeus.android.entities.Message> listMsg, Config config) {
		
		for (br.com.amadeus.android.entities.Message message : listMsg) {
			String endImageAuthor = config.getAmadeus_url() + 
			ConstantsAmadeusDroid.HOST_AMADEUS_WEB_PHOTO + message.getPersonLogin();
			try {
				ImageUtil.saveImageUser(endImageAuthor, message.getPersonLogin());
			} catch (ClientProtocolException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			} catch (IOException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			}
		}
		
	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.s2avancar:
			try {
				
				SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
				String pref = getPrefs.getString("listPref", "1");
				int opcao = Integer.parseInt(pref);
				
				switch (opcao) {
				case ConstantsAmadeusDroid.MODO_ONLINE:
					
					this.userLogin = login.getText().toString().trim();
					this.userPassword = password.getText().toString().trim();
					
					baseUrl = "";
	            	if (!end.getText().toString().trim().substring(0, 8).equals("http://")) {
						baseUrl = "http://";
					}else if (end.getText().toString().trim().equals(ConstantsAmadeusDroid.URL_LOCALHOST)) {
						baseUrl = "http://10.0.2.2:8080/";
					}
	            	
	            	endereco = baseUrl + end.getText().toString().trim();
	            	
					this.endereco = endereco + ConstantsAmadeusDroid.HOST_AMADEUS_WEB.trim();
						            	
					String url;
					RESTFileContent rfc = new RESTFileContent();
					
					if (this.userLogin.equals("") || this.userPassword.equals("") || this.endereco.equals("")) {
						Toast.makeText(FirstInnerSyncActivity.this, "Para o modo de acesso online, o preenchimento de todos os campos é obrigatório.\n" +
								"Caso queira acessar no modo offline, clique em Menu e em seguida em Configurações.", Toast.LENGTH_LONG).show();
					}else{
						
						String enderecoFinal = endereco + "/" + userLogin + "/" + userPassword;
						Log.i("LALA: ", enderecoFinal);
						boolean testHost = RESTFileContent.testHostValidation(enderecoFinal);
						if (testHost) {
							url = endereco.replace("service", "validate") + "/" + userLogin + "/" + userPassword;
							InputStream is = rfc.getRESTFileContent(url);
							String json = rfc.toString(is);
							boolean testUser = JSONReader.validateAccessInfo(json);
							if (testUser) {
								
								url = endereco.replace("service", "countcourses") + "/" + userLogin + "/" + userPassword;
								InputStream is2 = rfc.getRESTFileContent(url);
								String json2 = rfc.toString(is2);
								countCourses = JSONReader.countCourses(json2);
								if (countCourses > 0) {
									
									showDialog(PROGRESS_DIALOG);
									//while(syncThread.isAlive()){
									if(threadException){
										AlertDialog.Builder dialog = new AlertDialog.Builder(FirstInnerSyncActivity.this);
										dialog.setMessage("Conexão perdida. Tente novamente...");
										dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
											
											public void onClick(DialogInterface dialog, int which) {
												dialog.dismiss();
												dismissDialog(PROGRESS_DIALOG);
												
											}
										});
										dialog.show();
									}
									//}
								}else{
									Toast.makeText(FirstInnerSyncActivity.this, "Não há Cursos a serem sincronizados.", Toast.LENGTH_SHORT).show();
								}
								
							}else{
								Toast.makeText(FirstInnerSyncActivity.this, "Login ou Senha do Amadeus Inválidos ou Inexistentes.", Toast.LENGTH_SHORT).show();
							}
							
						}else{
							//Usuário sem conexão
							
							AlertDialog.Builder dialog = new AlertDialog.Builder(this);
							dialog.setMessage("Não foi possível realizar a Sincronização, verifique o acesso à Internet.");
							dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									
								}
							});
							dialog.show();
						}
						
					}
					
					break;

				case ConstantsAmadeusDroid.MODO_OFFLINE:
					
					if (facade.firstSyncronizing()) {
						AlertDialog.Builder dialog = new AlertDialog.Builder(this);
						dialog.setMessage("Não é possível realizar a primeira Sincronização no modo offline.");
						dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								
							}
						});
						dialog.show();
					}else{
			            Intent it = new Intent("HOME");
			            startActivity(it);
					}
					
										
					break;
				}
				
				
			} catch (ClientProtocolException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			} catch (JSONException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
				dialog.setMessage("Verifique se a URL do Amadeus está realmente correta.");
				dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						
					}
				});
				dialog.show();
			} catch (UnknownHostException e){
				//Usuário sem conexão
				
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
				dialog.setMessage("Não foi possível realizar a Sincronização, verifique o acesso à Internet.");
				dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						
					}
				});
				dialog.show();
			} catch (IOException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			}
			
			break;

		case R.id.s2voltar:
			
			Intent openStartingPoint = new Intent("FIRST_INNER");
			startActivity(openStartingPoint);
			
			break;
		}
		
	}
	
	private void initUrls(){
		
		ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, URLS);
		AutoCompleteTextView estatos = (AutoCompleteTextView) findViewById(R.id.etURL);
		estatos.setAdapter(adaptador);
	}
		
		
	 /** Nested class that performs progress calculations (counting) */
    private class ProgressThread extends Thread {
        Handler mHandler;
        final static int STATE_DONE = 0;
        final static int STATE_RUNNING = 1;
        int mState;
        int total;
        InputStream input;
        long lengthOfFile = 0;
        String courses;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
       
        ProgressThread(Handler h) {
            mHandler = h;
        }
       
        public void run() {
            mState = STATE_RUNNING;
            total = 0;
            
            try {
            	int read_byte = 0;            	
				String enderecoFinal = endereco + "/" + userLogin + "/" + userPassword;				
				RESTFileContent rfc = new RESTFileContent();
				InputStream is = rfc.getRESTFileContent(enderecoFinal);
				courses = rfc.toString(is);
				this.lengthOfFile = courses.length();
				rfc = new RESTFileContent();
				this.input = rfc.getRESTFileContent(enderecoFinal);
				
				
				if (this.lengthOfFile < 4800) {
					read_byte = 1;
				}else if ((this.lengthOfFile > 4801) && (this.lengthOfFile < 8700) ) {
					read_byte = 2;
				}else if (this.lengthOfFile > 8700) {
					read_byte = 3;
				}
                   	
				byte data[] = new byte[read_byte];
				int count = 0;
				
				String namePerson = JSONReader.getNamePerson(courses);
				
				Config config = new Config();
	            config.setId(0);
	            config.setAmadeus_url(baseUrl + end.getText().toString().trim());
	            config.setUser_login(login.getText().toString().trim());
	            config.setUser_name(namePerson);
	            config.setUser_password(password.getText().toString().trim());
	            config.setVersionSync(0);
				
				syncAmadeus(courses,countCourses,config);
								
				while (mState == STATE_RUNNING) {
					while ((count = this.input.read(data)) > 0) {
						total += count;
						// publishing the progress....
						baos.write(data, 0, count);
						Message msg = mHandler.obtainMessage();
		                msg.arg1 = (int)(total*100/lengthOfFile);
		                mHandler.sendMessage(msg);
					}
	            }
				
				while(syncThread.isAlive()){
				}
				if (!threadException) {
					Intent it = new Intent("HOME");
		            startActivity(it);
				}
				
				/*while(s){
					if (mState == STATE_DONE) {
						Intent it = new Intent("HOME");
			            startActivity(it);
			            break;
					}
				}*/
					            
			} catch (Exception e) {
				Log.e(CATEGORIA, e.getMessage(),e);
				dismissDialog(PROGRESS_DIALOG);
			}
            
            
        }
        
        
                
        /* sets the current state for the thread,
         * used to stop the thread */
        public void setState(int state) {
            mState = state;
        }
    }
}
